<template>
  <div>
    <el-dialog :visible="showDialog" :title="form.id ? '修改目录' : '添加目录'" width="400px" @open="onOpen" @close="onClose">
      <el-form ref="formRef" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-form-item v-if="subjectID === undefined" label="所属学科" prop="subjectName">
          <el-select v-model="form.subjectID" placeholder="请选择" :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in subjectNameOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="form.directoryName" placeholder="请输入目录名称" :style="{width: '100%'}">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { simple } from '../../api/hmmm/subjects'
import { add } from '../../api/hmmm/directorys'
export default {
  components: {},
  inheritAttrs: false,
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    subjectID: {
      type: String,
      default: () => undefined
    }
  },
  data() {
    return {
      form: {
        subjectID: undefined,
        directoryName: undefined
      },
      rules: {
        subjectName: [],
        directoryName: [{
          required: true,
          message: '请输入目录名称',
          trigger: 'blur'
        }]
      },
      subjectNameOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    // 获取学科列表
    this.getSubjectList()
  },
  mounted() {},
  methods: {
    async getSubjectList() {
      const { data } = await simple()
      // 下拉框获取列表
      this.subjectNameOptions = data
    },
    onOpen() {},
    onClose() {
      this.$emit('update:show-dialog', false)
      this.$refs.formRef.resetFields()
      this.form = {
        subjectName: undefined,
        directoryName: undefined
      }
    },
    handelConfirm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        // 如果是修改则有id需要上传id，如果为添加不需要上传id
        if (this.subjectID) {
          this.form.subjectID = Number(this.subjectID)
        }

        if (this.form.id) {
          await add(this.form)
        } else {
          // 发送请求添加目录
          await add(this.form)
        }
        this.$message.success('操作成功！')
        this.$parent.getTableDate()
        this.onClose()
      })
    }
  }
}

</script>
<style>
</style>
